<?php

declare(strict_types=1);

namespace app\controller\system\product;

use app\BaseController;
use app\model\ProdCategory;
use app\service\factory\ResponseFactory;
use app\service\product\CategoryService;
use app\validate\product\CategoryValidate;
use InvalidArgumentException;
use think\Response;
use Throwable;

class Category extends BaseController
{
    public function index(CategoryService $categoryService): Response
    {
        try {
            $asTree = filter_var($this->request->param('as_tree', false), FILTER_VALIDATE_BOOLEAN);
            $filters = $this->request->only([
                'keyword',
                'is_visible',
                'parent_id',
            ], 'get');

            if ($asTree) {
                $tree = $categoryService->tree($filters);
                return json(ResponseFactory::success($tree));
            }

            $page = max(1, (int) $this->request->param('page', 1));
            $pageSize = (int) $this->request->param('page_size', 20);
            $pageSize = $pageSize > 0 ? min($pageSize, 100) : 20;

            $paginator = $categoryService->paginate($filters, $page, $pageSize);
            $list = $categoryService->formatCollection($paginator->items());

            return json(ResponseFactory::paginated(
                $list,
                (int) $paginator->total(),
                $page,
                $pageSize
            ));
        } catch (Throwable $e) {
            return json(ResponseFactory::error($e->getMessage(), $e->getCode() ?: 500));
        }
    }

    public function read(int $id, CategoryService $categoryService): Response
    {
        try {
            $category = $categoryService->findById($id);
            if (!$category) {
                return json(ResponseFactory::error('分类不存在', 404));
            }

            return json(ResponseFactory::success($categoryService->format($category)));
        } catch (Throwable $e) {
            return json(ResponseFactory::error($e->getMessage(), $e->getCode() ?: 500));
        }
    }

    public function save(CategoryService $categoryService): Response
    {
        try {
            $payload = $this->request->only([
                'name',
                'slug',
                'parent_id',
                'icon_url',
                'cover_url',
                'description',
                'content',
                'sort',
                'is_visible',
            ], 'post');

            $this->validate($payload, CategoryValidate::class . '.create');

            $category = $categoryService->create($payload);

            return json(ResponseFactory::success($categoryService->format($category), '分类已创建'));
        } catch (InvalidArgumentException $e) {
            return json(ResponseFactory::error($e->getMessage(), 422));
        } catch (Throwable $e) {
            return json(ResponseFactory::error($e->getMessage(), $e->getCode() ?: 500));
        }
    }

    public function update(int $id, CategoryService $categoryService): Response
    {
        try {
            $category = ProdCategory::find($id);
            if (!$category) {
                return json(ResponseFactory::error('分类不存在', 404));
            }

            $payload = $this->request->only([
                'name',
                'slug',
                'parent_id',
                'icon_url',
                'cover_url',
                'description',
                'content',
                'sort',
                'is_visible',
            ], 'put');
            $payload['id'] = $id;

            $this->validate($payload, CategoryValidate::class . '.update');

            $updated = $categoryService->update($category, $payload);

            return json(ResponseFactory::success($categoryService->format($updated), '分类已更新'));
        } catch (InvalidArgumentException $e) {
            return json(ResponseFactory::error($e->getMessage(), 422));
        } catch (Throwable $e) {
            return json(ResponseFactory::error($e->getMessage(), $e->getCode() ?: 500));
        }
    }

    public function delete(int $id, CategoryService $categoryService): Response
    {
        try {
            $category = ProdCategory::find($id);
            if (!$category) {
                return json(ResponseFactory::error('分类不存在', 404));
            }

            if (!$categoryService->delete($category)) {
                return json(ResponseFactory::error('删除失败', 500));
            }

            return json(ResponseFactory::success(true, '分类已删除'));
        } catch (InvalidArgumentException $e) {
            return json(ResponseFactory::error($e->getMessage(), 422));
        } catch (Throwable $e) {
            return json(ResponseFactory::error($e->getMessage(), $e->getCode() ?: 500));
        }
    }
}
